﻿using System.ComponentModel.DataAnnotations;

namespace TK.Common.DataAnnotations
{
    /// <summary>
    /// Specifies the minimum value allowed in a property.
    /// </summary>
    public class MinValueAttribute : ValidationAttribute
    {
        /// <summary>
        /// ctor
        /// </summary>
        public MinValueAttribute(int minValue, bool includeMinValue = true)
        {
            MinValue = minValue;
            IncludeMinValue = includeMinValue;
        }

        /// <summary>
        /// 最小值
        /// </summary>
        public decimal MinValue { get; set; }

        /// <summary>
        /// 是否包含最小值
        /// </summary>
        public bool IncludeMinValue { get; set; }

        /// <summary>
        /// Determines whether the specified value of the object is valid.
        /// </summary>
        public override bool IsValid(object value)
        {
            if (value != null)
            {
                if (decimal.TryParse(value.ToString(), out var curVal))
                {
                    return IncludeMinValue ? curVal >= MinValue : curVal > MinValue;
                }
            }

            return true;
        }
    }
}
